package com.fhao.java_gobang.utils;

import com.fhao.java_gobang.constant.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtils {
    private static final long JWT_EXPIRATION = 60 * 60 * 1000;
    private static final String secretStr = "PSjluLOQC1hMkku3vJWi9Z+DVABEMZ5zBgoz7DiqphY=";
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretStr));

    /**
     * 生成令牌
     */
    public static String genJwt(Map<String,Object> claim) {
        String token = Jwts.builder().setClaims(claim)
                .signWith(key)
                .setExpiration(new Date(System.currentTimeMillis()+JWT_EXPIRATION))
                .compact();
        return token;
    }

    /**
     * 校验token
     * 校验的过程中,只要不抛出异常都是校验成功,抛出异常就说明校验失败.
     * claim 为 null表示校验失败, 不为 null 表示校验成功.
     */
    public static Claims parseToken(String token) {
        //设置解析key,并拿到解析器
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e) {
            log.error("校验token失败,token: {}",token);
            return null;
        }
        return claims;
    }

    /**
     * 从token中拿到 id
     */
    public static Integer getIdByToken(String token) {
        Claims claims = parseToken(token);
        if(claims == null) {
            return null;
        }
        Integer userId = (Integer) claims.get(Constants.TOKEN_ID);
        if(userId > 0) {
            return userId;
        }
        return null;
    }

}
















